import 'package:easy_debounce/easy_throttle.dart';
import 'package:flutter/material.dart';
import 'package:lib_uikit/generated/l10n.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lib_uikit/utils/gt_native_viewpager_scroll_fix.dart';
import 'package:lib_uikit/widgets/gt_page_scroll_physics.dart';

/// @author dayo
/// @created at 2024/4/2 20:39
/// @desc: 左右滑动 没有指示器, 末尾添加moreButton
///
class GTSliverMoreBanner extends StatefulWidget {
  const GTSliverMoreBanner({
    super.key,
    required this.itemBuilder,
    required this.itemCount,
    required this.cardWidth,
    required this.cardSpacing,
    required this.cardStartMargin,
    required this.cardEndMargin,
    this.onPageChange,
    this.onPageChangeCompleted,
    this.moreClickAction,
    this.controller,
  });

  final Widget? Function(BuildContext context, int index) itemBuilder;
  final int itemCount;
  final Function(int page)? onPageChange;
  final Function(int oldPage, int newPage)? onPageChangeCompleted;
  final VoidCallback? moreClickAction;
  final ScrollController? controller;

  final double cardWidth;

  /// 卡片间隔
  final double cardSpacing;

  /// 卡片左侧边距（用于计算卡片的起始位置，计算卡片滚动时中心点，）
  final double cardStartMargin;
  final double cardEndMargin;

  @override
  State<GTSliverMoreBanner> createState() => _GTSliverMoreBannerState();
}

class _GTSliverMoreBannerState extends State<GTSliverMoreBanner> {
  ScrollController? _controller;
  int currentPage = 0;
  int currentPageCompleted = 0; //onPageChangeCompleted有值时 才生效
  List<Widget> children = [];

  ScrollController get controller {
    if (widget.controller != null) {
      return widget.controller!;
    }
    _controller ??= ScrollController();
    return _controller!;
  }

  @override
  void initState() {
    controller.addListener(_scrollerAction);
    // widget.children.forEachIndexed((index, element) {
    //   //添加
    //   children.add(SizedBox(width: widget.cardWidth, child: element));
    //   //间距
    //   if (index + 1 < widget.children.length) {
    //     children.add(SizedBox(width: widget.cardSpacing));
    //   }
    // });
    // if (widget.moreClickAction != null) {
    //   children.add(SizedBox(width: widget.cardSpacing));
    //   children.add(GestureDetector(
    //     behavior: HitTestBehavior.opaque,
    //     onTap: () {
    //       EasyThrottle.throttle('GTSliverMoreBanner', const Duration(milliseconds: 500), () {
    //         widget.moreClickAction!();
    //       });
    //     },
    //     child: Container(
    //       width: 77,
    //       decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: GTColorsV3.neutral1.color),
    //       alignment: Alignment.center,
    //       child: Text(
    //         LibUIKitS.current.uikit_more,
    //         style: TextStyle(fontSize: 12, color: GTColorsV3.text1.color, fontWeight: FontWeight.w500),
    //       ),
    //     ),
    //   ));
    // }
    // if (widget.cardEndMargin > 0) {
    //   children.add(SizedBox(width: widget.cardEndMargin));
    // }
    super.initState();
  }

  @override
  void dispose() {
    //外部控制器不做dispose
    controller.removeListener(_scrollerAction);
    //只dispose内部的控制器
    _controller?.dispose();
    super.dispose();
  }

  _scrollerAction() {
    int page = 0;
    if (controller.offset > widget.cardStartMargin) {
      double total = controller.offset + (GTScreen.width / 2 - widget.cardWidth / 2 - widget.cardStartMargin);
      page = (total / (widget.cardWidth + widget.cardSpacing)).round();
    }
    if (currentPage != page) {
      currentPage = page;
      if (widget.onPageChange != null) {
        widget.onPageChange!(page);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.onPageChangeCompleted != null) {
      return NotificationListener<ScrollEndNotification>(
        onNotification: (notification) {
          widget.onPageChangeCompleted!(currentPageCompleted, currentPage);
          currentPageCompleted = currentPage;
          return true;
        },
        child: _buildMainWidget(),
      );
    }
    return _buildMainWidget();
  }

  _buildMainWidget() {
    return ListView.separated(
      physics: GTPageScrollPhysics(
        cardWidth: widget.cardWidth,
        cardSpacing: widget.cardSpacing,
        cardStartMargin: widget.cardStartMargin,
        parent: const PageScrollPhysics(),
      ),
      scrollDirection: Axis.horizontal,
      padding: GTEdgeInsetsOnly(left: widget.cardStartMargin, right: widget.cardEndMargin),
      controller: controller,
      itemBuilder: (BuildContext context, int index) {
        if (widget.moreClickAction != null && index == widget.itemCount) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              EasyThrottle.throttle('GTSliverMoreBanner', const Duration(milliseconds: 500), () {
                widget.moreClickAction!();
              });
            },
            child: Container(
              width: 77,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: GTColorsV3.neutral1.color),
              alignment: Alignment.center,
              child: Text(
                LibUIKitS.current.uikit_more,
                style: TextStyle(fontSize: 12, color: GTColorsV3.text1.color, fontWeight: FontWeight.w500),
              ),
            ),
          );
        }
        return SizedBox(width: widget.cardWidth, child: widget.itemBuilder(context, index));
      },
      separatorBuilder: (BuildContext context, int index) {
        return SizedBox(width: widget.cardSpacing);
      },
      itemCount: widget.moreClickAction != null ? widget.itemCount + 1 : widget.itemCount,
      // children: children,
    );
  }
}
